package com.spmsys.filter;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

@WebFilter(filterName = "ContentTypeFilter", urlPatterns = "/controller/*")
public class A_ContentTypeFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            String contentType = httpServletRequest.getContentType();
            String method = httpServletRequest.getMethod();
            if (!contentType.contains("application/json")) {
                throw new RuntimeException("contentType仅支持application/json");
            }
            if (!method.equals("POST")) {
                throw new RuntimeException("method仅支持POST");
            }
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            //获取当前时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            //设置字符集、接受所有跨域请求、设置时间
            httpServletResponse.setContentType("application/json;charset=utf-8");
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
            httpServletResponse.setHeader("Date", simpleDateFormat.format(Calendar.getInstance().getTime()));
            JSONObject responseData = new JSONObject();
            responseData.put("errorCode", "CONTENT_TYPE_FILTER_FAIL");
            responseData.put("errorMessage", e.getMessage());
            PrintWriter printWriter = httpServletResponse.getWriter();
            printWriter.println(responseData);
            printWriter.close();
            e.printStackTrace();
        }
    }
}
